class Document < ActiveRecord::Base
	
	extend Permissible
	
    attr_accessible :name, :description, :authors, :publication_date, :related_work, :owner,
		:categories, :tags, :files, :comments, :created_by, :updated_by
	
	translates :name, :description
	
	# Validations:
	validates :name, presence: true
	validates :owner, presence: true
	validates :categories, presence: true
	validates :files, presence: true
    
    # Relationships:
    belongs_to :owner, class_name: 'User'
    has_and_belongs_to_many :categories
    has_and_belongs_to_many :tags
    has_many :files, class_name: 'DataFile', dependent: :destroy
	has_many :comments, dependent: :destroy
	
	accepts_nested_attributes_for :tags
	accepts_nested_attributes_for :files
	
	# Internal path to the documents file storage
    def storage_path
        "public/files/#{self.id}"
    end
    
    def remove
        FileUtils.rm_rf(storage_path) #remove directory with all files
		self.destroy
    end
	
	def self.create_with_default_permissions(params)
		params[:publication_date] = Date.parse(params[:publication_date]) unless params[:publication_date].blank?
		
		# Handle files and tags separately, not in the documents constructor
        files_param = params[:files]
        params.delete(:files)
		
		tags_param = params[:tags]
        params.delete(:tags)		
        
		document = Document.new(params)
		document.tags = Tag.string_to_tags(tags_param, params[:owner], document)
        
		unless files_param.nil?
			f = DataFile.save(files_param, document) # Single file upload
			# outcommented code is for multiple files upload
			#files = DataFile.save_files(files_param, document)
			#files.each do |f|
				document.files.build(
					path: f.path.sub('public/', ''),	# strip 'public/' as it's not needed for the URL
					mime_type: MIME::Types.type_for(f.path).first.content_type, 
					file_size: f.size,
					created_by: document.owner.id)
			#end
		end
        
        document.save
		
		if document.errors.none?
			create_default_owner_permissions(document, document.owner)
		end
		
		return document
	end
	
	def self.search(search, in_category_ids=[])
		if search
			# Differentiate whether search is limited to certain categories or it's unlimited
			if in_category_ids.blank?
				search_space = Document
			else
				search_space = joins(:categories)
					.where('categories_documents.category_id IN (?)', in_category_ids)
			end
			
			search_space.where('document_translations.name ILIKE :search_term 
						OR document_translations.description ILIKE  :search_term',
					search_term: "%#{search}%")
		else
			scoped
		end
	end

    def file
		files.first
    end
end
